package com.songyuesheng.app.service.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.songyuesheng.app.commom.LuckyLogs;
import com.songyuesheng.app.entity.Logs;
import com.songyuesheng.app.entity.User;
import com.songyuesheng.app.service.LogsService;
import com.songyuesheng.app.util.IpUtils;
import com.songyuesheng.app.util.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
@Slf4j
public class LogsAspect {

    @Resource
    LogsService logsService;

    @AfterReturning(pointcut = "@annotation(luckyLogs)", returning = "jsonResult")
    public void recordLog(JoinPoint joinPoint, LuckyLogs luckyLogs, Object jsonResult) {
        // 获取当前登录的用户的信息
        User loginUser = JwtUtil.getCurrentUser();
        if (loginUser == null) { // 用户未登录的情况下  loginUser是null  是null的话我们就要从参数里面获取操作人信息
            // 登录、注册
            Object[] args = joinPoint.getArgs();
            if (ArrayUtil.isNotEmpty(args)) {
                if (args[0] instanceof User) {
                    loginUser = (User) args[0];
                }
            }
        }
        if (loginUser == null) {
            log.error("记录日志信息报错，未获取到当前操作用户信息");
            return;
        }
        // 获取HttpServletRequest对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();

        log.info("User ID: {}, Username: {},URI: {}, Method: {},Executing method: {}",
                loginUser.getId(),
                loginUser.getUsername(),
                request.getRequestURI(),
                request.getMethod(),
                joinPoint.getSignature().getName());
        // 获取到请求的ip
        String ip = IpUtils.getIpAddr(request);
        Logs logs = Logs.builder()
                .operation(luckyLogs.operation())
                .type(luckyLogs.type().getValue())
                .ip(ip)
                .user(loginUser.getUsername())
                .time(DateUtil.now())
                .build();

        ThreadUtil.execAsync(() -> {
            // 异步记录日志信息
            logsService.save(logs);
        });
    }

}